package com.liveneo.adapter.mobile.util;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.system.base.utils.LtUtils;

/**
 * @Title: OSS文件服务器操作类
 * @Description:
 * @Author:YJX
 * @Since:2015-8-22 下午12:58:58
 * @Version:1.0.0
 * @Copyright (c) 北京朗泰恒盛信息技术有限公司-版权所有
 */
public class OssManage {
    public static String   ACCESS_KEY_ID     = null;
    public static String   ACCESS_KEY_SECRET = null;
    public static String   ENDPOINT          = null;   // 公网地址
    public static String   ENDPOINT_INTERNAL = null;  // 内网地址
    public static String   BUCKETNAME        = null;
    public static String   SUBBUCKETNAME     = null;
    public static String   BUCKETNAME_VIDEO  = null;
    public static String   OUT_OF_DATE       = null;
    private OSSClient      client            = null;
    private ObjectMetadata meta              = null;
    static {
        try {
            ACCESS_KEY_ID = PropertyConfigurer.getValue("oss.access.key.id");
            ACCESS_KEY_SECRET = PropertyConfigurer.getValue("oss.access.key.secret");
            ENDPOINT = PropertyConfigurer.getValue("oss.endpoint");
            ENDPOINT_INTERNAL = PropertyConfigurer.getValue("oss.endpoint.internal");
            BUCKETNAME = PropertyConfigurer.getValue("oss.bucket.name");
            SUBBUCKETNAME = PropertyConfigurer.getValue("oss.bucket.name.zte");
            BUCKETNAME_VIDEO = PropertyConfigurer.getValue("oss.bucket.name.zte");
            OUT_OF_DATE = PropertyConfigurer.getValue("oss.out.of.date");
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
    }

    public void init() {
        // 初始化一个OSSClient
        if (client == null) {
            client = new OSSClient(ENDPOINT_INTERNAL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        }
        if (meta == null) {
            meta = new ObjectMetadata();
        }
    }

    /**
     * @Description: 上传文件到OSS文件服务器
     * @param content
     *                文件流
     * @param key
     *                上传为OSS文件服务器的唯一标识
     * @param mimeType
     *                文档类型
     * @throws Exception
     * @ReturnType:String OSSObject的ETag值。
     * @exception
     * @Since:2015-8-22 下午02:00:19
     * @Author:YJX
     */
    public String uploadFile(InputStream content, String key, String mimeType, String loguuid) throws Exception {
        // 进行初始化 TODO 改成局部变量 或 改成单例模式
        init();
        // 必须设置ContentLength
        meta.setContentType(mimeType);
        // 上传Object.
        LogUtils.info("*****************uploadFile上传图片到oss服务器开始>loguuid=" + loguuid + "*****************" + key);
        LogUtils.info("*****************uploadFile上传图片到oss服务器开始>loguuid=" + loguuid + ">client state:" + client);
        PutObjectResult result = client.putObject(BUCKETNAME, key, content, meta);
        meta.wait(500);
        client.shutdown();// 上传完成后关闭
        LogUtils.info("*****************uploadFile上传图片到oss服务器结束>loguuid=" + loguuid + "*****************" + key);
        return result.getETag();
    }

    /**
     * @Description: 根据key获取oss服务器上的图片公网地址
     * @param key
     * @return
     * @ReturnType:String
     * @exception
     * @Since:2015-8-26 下午04:57:46
     * @Author:YJX
     */
    public String getImgURl(String key) {
        // init();
        LogUtils.info("*****************getImgURl开始*****************" + key);
        if (LtUtils.isEmpty(key)) {
            return "";
        }
        client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        meta = new ObjectMetadata();
        Date expires = new Date(new Date().getTime() + Integer.parseInt(OUT_OF_DATE)); // 30
        GeneratePresignedUrlRequest generatePresignedUrlRequest;
        if (key.startsWith("MP")) {
            generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, SUBBUCKETNAME + File.separator + key);
        } else {
            generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME_VIDEO, key);
        }
        generatePresignedUrlRequest.setExpiration(expires);
        URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
        LogUtils.info("*****************getImgURl结束*****************" + key + "************" + url.toString());
        return url.toString();
    }

    /**
     * @Description:根据key获取oss服务器上的ipa文件公网地址
     * @param key
     * @return
     * @ReturnType:String
     * @exception
     * @Since:2015-11-3 下午02:35:42
     * @Author:yleilei
     */
    public String getIpaURl(String key) {
        LogUtils.info("*****************getIpaURl开始*****************" + key);
        client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        Date expires = new Date(new Date().getTime() + 10 * 365 * 24 * 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest;
        if (key.startsWith("MP")) {
            generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, key);
        } else {
            generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME_VIDEO, key);
        }
        generatePresignedUrlRequest.setExpiration(expires);
        URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
        LogUtils.info("*****************getIpaURl结束*****************" + key + "*************" + url.toString());
        return url.toString();
    }

    /**
     * @Description: 根据key获取oss服务器上的图片地址
     * @param key
     * @return
     * @ReturnType:String
     * @exception
     * @Since:2015-8-26 下午04:57:46
     * @Author:YJX
     */
    public InputStream getObject(String key) {
        init();
        OSSObject object = null;
        if (key.startsWith("MP")) {
            object = client.getObject(BUCKETNAME, key);
        } else {
            object = client.getObject(BUCKETNAME_VIDEO, key);
        }
        object.getObjectMetadata().getContentType();
        // 获取Object的输入流
        InputStream objectContent = object.getObjectContent();
        return objectContent;
    }

    /**
     * @Description:删除文件
     * @param key
     *                OSS文件服务器上文件的唯一标识
     * @ReturnType:void
     * @exception
     * @Since:2015-8-22 下午02:21:23
     * @Author:YJX
     */
    public void deleteFile(String key) {
        init();
        client.deleteObject(BUCKETNAME, key);
    }

    /**
     * @Description: 断点上传文件到OSS文件服务器
     * @param content
     *                文件流
     * @param key
     *                上传为OSS文件服务器的唯一标识
     * @param position
     *                位置
     * @throws Exception
     * @ReturnType:String appendObjectResult.getNextPosition().toString()。
     * @exception
     * @Since:2015-10-10 下午04:00:19
     * @Author:zhoupan
     */
    public String appendObjectFile(InputStream content, String key, int position, String mimeType) throws Exception {
        // 进行初始化
        init();
        // 必须设置ContentLength
        meta.setContentLength(position);
        meta.setContentType(mimeType);
        meta.setCacheControl("no-cache");
        meta.setContentEncoding("utf-8");
        // 上传
        LogUtils.info("*****************断点上传图片到oss服务器开始*****************" + key);
        AppendObjectRequest appendObjectRequest = new AppendObjectRequest(BUCKETNAME, key, content, meta);
        appendObjectRequest.setPosition(Long.valueOf(position));
        AppendObjectResult appendObjectResult = client.appendObject(appendObjectRequest);
        LogUtils.info("*****************断点上传图片到oss服务器结束*****************" + key);
        return appendObjectResult.getNextPosition().toString();
    }

    public static void main(String[] args) {
        OssManage ossManage = new OssManage();
    }
}
